import line from 'helpers/line';
import merge from 'lodash/merge';

const WORKING = 'CLASS_WORKING';
const GET_CLASS_SUCCESS = 'GET_CLASS_SUCCESS';
const GET_CLASS_FAIL = 'GET_CLASS_FAIL';
const GET_OBJECT_SUCCESS = 'GET_OBJECT_SUCCESS';
const GET_OBJECT_FAIL = 'GET_OBJECT_FAIL';
const GET_SCHEMA_SUCCESS = 'GET_SCHEMA_SUCCESS';
const GET_SCHEMA_FAIL = 'GET_SCHEMA_FAIL';

const initialState = {
  working: false
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case WORKING:
      return {
        ...state,
        working: true
      };
    case GET_SCHEMA_SUCCESS:
      const classNameSchema = action.className;
      return {
        ...state,
        [classNameSchema]: merge({}, state[classNameSchema], { schema: action.result })
      };
    case GET_SCHEMA_FAIL:
      return {
        ...state,
        error: action.error
      };
    case GET_CLASS_SUCCESS:
      const classNameClass = action.className;
      return {
        ...state,
        [classNameClass]: merge({}, state[classNameClass], { data: action.result.results })
      };
    case GET_CLASS_FAIL:
      return {
        ...state,
        error: action.error
      };
    case GET_OBJECT_SUCCESS:
      return {
        ...state,
        object: action.result
      };
    case GET_OBJECT_FAIL:
      return {
        ...state,
        error: action.error
      };
    default:
      return state;
  }
}


export function getClass(className) {
  return {
    types: [WORKING, GET_CLASS_SUCCESS, GET_CLASS_FAIL],
    promise: () => line.get(className),
    className
  };
}

export function getObject(className, objectId) {
  return {
    types: [WORKING, GET_OBJECT_SUCCESS, GET_OBJECT_FAIL],
    promise: () => line.get(className, { objectId })
  };
}

export function getSchema(className) {
  return {
    types: [WORKING, GET_SCHEMA_SUCCESS, GET_SCHEMA_FAIL],
    promise: () => line.getSchemas(className),
    className
  };
}
